package com.application.admin;

import com.jfinal.ext.tree.TreeUtil;
import com.jfinal.ext.tree.ZtreeNode;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.platform.annotation.Controller;
import com.platform.mvc.base.BaseController;
import com.platform.mvc.menu.Menu;
import com.platform.mvc.menu.MenuService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 菜单管理
 */
@Controller("/admin/menu")
public class MenuController extends BaseController {

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(MenuController.class);

    MenuService menuService;

    /**
	 * 菜单管理首页
	 */
	public void index() {

        String roleid = super.getCUser().getStr("role_id");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("names", "names" + geti18nColumnSuffix() + " as names");

        String oneSql = getSqlByBeetl(Menu.sqlId_child, param);
//        String twoSql = getSqlByBeetl(Menu.sqlId_operator, param);
        String twoSql = getSqlByBeetl("platform.menu.operator2", param);

        // 查询根菜单节点
        Menu menu = Menu.dao.findFirst("select ids from pt_menu where parentmenuids is null");
        String parentmenuids = menu.getPKValue();

        // 一级菜单
//        List<Menu> oneList = Menu.dao.find(twoSql, parentmenuids, userIds, userIds);
        List<Menu> oneList = Menu.dao.find(oneSql, parentmenuids);
        for (Menu oneMenu : oneList) {
            // 二级菜单
            String pMenuIds = oneMenu.getPKValue();
//            List<Menu> twoList = Menu.dao.find(twoSql, pMenuIds, userIds, userIds);
            List<Menu> twoList = Menu.dao.find(twoSql, pMenuIds, roleid);
            List<Menu> subList = twoList.stream().filter(o-> (o.get("disable") == null || o.getInt("disable") ==0))
                    .collect(Collectors.toList());
            oneMenu.put("subList", subList);
        }

        /*
        过滤掉无子菜单的一级菜单
         */
        List<Menu> resultList = oneList.stream().filter(o -> ((List<Menu>) o.get("subList")).size() > 0).collect(Collectors.toList());

        renderOk(resultList);
	}


    public void treeData() {
        List<Menu> menus = Menu.dao.findList();

        String cxt = getCxt();
        List<ZtreeNode> nodeList = new ArrayList<>();
        ZtreeNode node = null;

        for (Menu menu : menus) {
            String icon = menu.getStr("icon");
            if(StrKit.isBlank(icon)){
                icon = "";
            }
            node = new ZtreeNode();
            node.setId(menu.getPKValue());
            node.setName(menu.getStr("names_zhcn"));
            node.setParentId(menu.getParentmenuids());
            node.setIcon("<i class=\"iconfont\">" + icon + "</i>");
            node.setOrd(menu.get(Menu.column_orderids));
            node.setOperator(menu.getOperator()== null ? "" : menu.getOperator().getNames());
            nodeList.add(node);
        }

        TreeUtil.setRootCode("");
        List<ZtreeNode> ztreeNodes = TreeUtil.getJsonList(nodeList);

        renderOk("", "成功", ztreeNodes);
    }

    /*
    @param {parentids}
     */
    public void save() {
        Menu obj = new Menu();

        String pid = getPara("parentmenuids") == null ? "root" : getPara("parentmenuids");
        Menu pd = Menu.dao.findById(pid);
        obj.setLevels((pd.getInt(Menu.column_levels)) + 1);
        obj.setParentmenuids(pid);
        obj.setNames_zhcn(getPara("names_zhcn"));
        obj.setOperatorids(getPara("operatorids"));
        obj.set(Menu.column_orderids, getParaToInt("orderids"));
        obj.set("icon", getPara("icon"));

        if ("false".equals(pd.getIsparent())) {
            pd.setIsparent("true");
            pd.update();
        }

        if(obj.save()){
            renderOk("reload", "添加成功", null);
        } else {
            renderErr(400, "", "保存失败");
        }
    }


    public void updateOptional() {

        String did = getPara() == null ? ids : getPara();
        String orderids = getPara("orderids");
        String name = getPara("names_zhcn");
        String pid = getPara("parentmenuids");
        Menu menu = new Menu();
        menu.setIds(did);

        if (!StrKit.isBlank(orderids)) {
            menu.setOrderids(Long.parseLong(orderids));
        }

        if (!StrKit.isBlank(name)) {
            menu.setNames_zhcn(name);
        }

        if (!StrKit.isBlank(pid)) {
            Menu pd = Menu.dao.findById(pid);
            menu.setLevels(pd.getInt(Menu.column_levels) + 1);
            menu.setParentmenuids(pid);
        }

        if(menu.update()){
            renderOk("refresh", "修改成功", null);
        } else {
            renderErr(400, "", "修改失败");
        }

    }

    public void update() {
        String pid = getPara("parentmenuids") == null ? "root" : getPara("parentmenuids");
        Menu pd = Menu.dao.findById(pid);
//        Menu obj = Menu.dao.getModelByMap(getPara() == null ? ids : getPara(), super.getParamMap());
        Menu obj = new Menu();

        obj.setLevels((pd.getInt(Menu.column_levels)) + 1);
        obj.setParentmenuids(pid);
        obj.setNames_zhcn(getPara("names_zhcn"));
        obj.setOperatorids(getPara("operatorids"));
        obj.set(Menu.column_orderids, getParaToInt("orderids"));
        obj.setIds(getPara());
        obj.set("icon", getPara("icon"));
        obj.set("disable", getPara("disable"));

        obj.update();

        if ("false".equals(pd.getIsparent())) {
            pd.setIsparent("true");
            pd.update();
        }
        renderOk("refresh", "修改成功", null);
    }

    /**
     * 删除
     */
    public void delete() {
        menuService.baseDelete(Menu.table_name, ids == null ? getPara("checkbox") : ids);
        renderOk("", "删除成功", null);
    }

    public void view(){
        Menu menu = Menu.dao.findDetail(getPara());
        renderOk(menu);
    }
}


